﻿using System.Collections.Generic;
using System.Linq;
using System.Web.UI;

namespace Cms.Web.Framework.Extensions
{
    public static class ControlExtensions
    {
        public static IEnumerable<Control> AllControls(this Control control)
        {
            IEnumerable<Control> children = control.Controls.Cast<Control>();
            return children.SelectMany(c => AllControls(c)).Concat(children);
        }
        
        public static IEnumerable<T> FindAllControlsOfType<T>(this Control control)
        {
            IList<Control> controls = new List<Control>();
            FindAllControlsOfTypeRecursive<T>(control, ref controls);
            return controls.Cast<T>();
        }
        
        private static void FindAllControlsOfTypeRecursive<T>(Control control, ref IList<Control> children)
        {
            foreach (Control c in control.Controls)
                if (c is T)
                {
                    children.Add(c);
                    FindAllControlsOfTypeRecursive<T>(c, ref children);
                }
        }
    }
}